<?php
// +----------------------------------------------------------------------
// | HkCms
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\admin\controller;

use app\admin\model\Model;
use think\facade\Db;
use think\facade\Validate;

class Friendlinks extends BaseController
{
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [
        'login',
        'auth'
    ];

    /**
     * 推荐位模型
     * @var \app\admin\model\Friendlinks
     */
    protected $model;

    /**
     * 允许批量修改的字段
     * @var array
     */
    protected $allowFields = ['status','weigh','new_window'];

    /**
     * 初始化操作
     */
    public function initialize()
    {
        parent::initialize();

        $this->model = new \app\admin\model\Friendlinks();
    }

    public function index()
    {
        // if ($this->request->isAjax()) {
            // $lang = $this->request->param('clang', $this->contentLang);
            // if (site('content_lang_on')==1) {
                // $list = $this->model->where(['lang'=>$lang])->paginate(10);
            // } else {
                // $list = $this->model->where(['lang'=>''])->paginate(10);
            // }
            // $total = $list->total();
            // $data = $list->toArray()['data'];
            // return json(['total'=>$total,'rows'=>$data]);
        // }
        // return $this->view->fetch();
		
		if ($this->request->isAjax()) {

            if ($this->request->param('searchTable')) {
                return $this->selectPage(); // 判断请求。如果是动态下拉组件请求，则交接给selectPage方法
            }
			$lang = $this->request->param('clang', $this->contentLang);
            list($map, $limit, $offset, $order, $sort) = $this->buildparams();
			if (site('content_lang_on')==1) {
                $map[] = ['lang','=',$lang];
            }
			$data = $this->model->where($map)->order($sort, $order)->limit($offset, $limit)->select();
			$total = $this->model->where($map)->order($sort, $order)->count();
            return json(['total'=>$total,'rows'=>$data]);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return mixed|string|void
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $row = $this->request->param('row/a','',null);
            $admin_id = $this->user->id;

            $data = [
                'admin_id' => $admin_id,
                'type' => $row['type'],
				'name' => $row['name'],
				'image' => $row['image'],
                'url' => $row['url'],
            ];
            //$this->validate($data, ['name'=>'require|alphaDash'], ['name.alphaDash'=>'标识只能是字母、数字和下划线_及破折号-']);

            // 判断唯一
            $tmpId = \app\admin\model\Friendlinks::where(['name'=>$row['name'],'lang'=>$this->contentLang])->value('id');
			if ($tmpId) {
                $this->error(lang('%s,existed',[$row['name']]));
            }
			$data['lang'] = '';
            Db::startTrans();
            try {
                $result = $this->model->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
				$this->cache->clear();
				$this->success();
            } else {
				$this->error(lang('No rows added'));
            }
			$this->error(lang('No rows added'));
        }
		return $this->view->fetch();
    }

    /**
     * 修改
     * @param null $id
     */
    public function edit($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(lang('Record does not exist'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a",'',null);
            if ($params) {
                $admin_id = $this->user->id;
                $data = [
                    'admin_id' => $admin_id,
                    'type' => $params['type'],
					'name' => $params['name'],
					'image' => $params['image'],
                    'url' => $params['url']
                ];
                //$this->validate($data, ['name'=>'require|alphaDash'], ['name.alphaDash'=>'标识只能是字母、数字和下划线_及破折号-']);
                if (Db::name('friendlinks')->where(['name'=>$data['name'],'lang'=>$row['lang']])->where('id','<>', $row['id'])->value('id')) {
                    $this->error(lang('Friendlinks already exists'));
                }
				
				$result = false;
                Db::startTrans();
                try {
                    $result = $row->save($data);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                if ($result !== false) {
                    $this->cache->clear();
                    $this->success();
                } else {
                    $this->error(lang('Unmodified record'));
                }
            }
            $this->error(lang('Parameter is empty'));
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
        //return $this->view->fetch('', compact('row'));
    }
}